package com.app.micaihu.videoplayer;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.ad.AdConfig;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.ad.NativeAd;
import com.app.micaihu.bean.ad.NativeAdVideo;
import com.app.micaihu.bean.news.ShareBean;
import com.app.micaihu.bean.news.VideoContent;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.utils.AppShareUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.view.main.game.GameDetailActivity;
import com.app.micaihu.view.newsdetail.VideoDetailActivity;
import com.app.utils.util.StringUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.baidu.mobstat.StatService;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 标准播放器
 * Created by Nathen
 * On 2016/04/18 16:15
 */
public class JCVideoPlayerStandard extends JCVideoPlayer {

    protected static Timer DISMISS_CONTROL_VIEW_TIMER;

//    private static List<String> adListId = new ArrayList<>();//播放过广告的文章id 一个视频只放一次

    public ImageView backButton;//退出全屏按钮
    public ProgressBar bottomProgressBar, loadingProgressBar;//下方进度条
    public TextView titleTextView;//标题
    public CustomImageView thumbImageView;//封面图
    public ImageView tinyBackImageView;//叉叉
    public View replyLayout;//重播模块


    //    protected BaiduNativeVideoView adView;//广告控件
//    protected NativeAdVideo nativeAdVideo;//视频广告数据
//    private boolean isAdFinishChangeUI = true;//广告加载完成后是否展示
    private boolean isShowTitle = true;//是否显示标题
    private AppShareUtils mShareUtils;//分享工具
    private String videoType;//视频类型
    protected DismissControlViewTimerTask mDismissControlViewTimerTask;
    private ImageView smallStartButton;
    private String adId;
    private View tiaoguoBtn;


    private static HashMap<String, Integer> adPlayedSet;


    private static HashMap<String, String> adMap = new HashMap<>();
    private String articleId;
    private int apPlayNum;//广告播放的次数

    private static String adIdStr = "";//广告的字符串
    private View chakanBtn;


    public JCVideoPlayerStandard(Context context) {
        super(context);
    }

    public JCVideoPlayerStandard(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public JCVideoPlayerStandard(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void init(Context context) {
        super.init(context);
        bottomProgressBar = (ProgressBar) findViewById(R.id.bottom_progress);
        titleTextView = (TextView) findViewById(R.id.title);
        backButton = (ImageView) findViewById(R.id.back);
        thumbImageView = (CustomImageView) findViewById(R.id.thumb);
        loadingProgressBar = (ProgressBar) findViewById(R.id.loading);
        tinyBackImageView = (ImageView) findViewById(R.id.back_tiny);
        replyLayout = findViewById(R.id.jc_reply_layout);

        smallStartButton = (ImageView) findViewById(R.id.startSmall);

        smallStartButton.setOnClickListener(this);
        tiaoguoBtn = findViewById(R.id.tiaoguoBtn);
        chakanBtn = findViewById(R.id.chakanBtn);


        findViewById(R.id.jc_replay).setOnClickListener(this);
        findViewById(R.id.jc_share).setOnClickListener(this);
        thumbImageView.setOnClickListener(this);

        backButton.setOnClickListener(this);
        tinyBackImageView.setOnClickListener(this);
        tiaoguoBtn.setOnClickListener(this);
        chakanBtn.setOnClickListener(this);

    }

    @Override
    public void setUp(String url, int screen, Object... objects) {
        super.setUp(url, screen, objects);
        if (objects.length == 0) {
            titleTextView.setVisibility(View.GONE);
            return;
        } else if (objects.length == 1) {
            titleTextView.setText(objects[0].toString());
        } else if (objects.length >= 2) {
            titleTextView.setText(objects[0].toString());
            LoadImageUtils.getInstance().loadWifiImage(thumbImageView, objects[1].toString());
        } else if (objects.length >= 3) {
            titleTextView.setText(objects[0].toString());
            LoadImageUtils.getInstance().loadWifiImage(thumbImageView, objects[1].toString());
            timeTextview.setText(objects[2].toString());
        }

        if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
            fullscreenButton.setImageResource(R.drawable.jc_shrink);
            backButton.setVisibility(View.VISIBLE);
            tinyBackImageView.setVisibility(View.INVISIBLE);
            changeStartButtonSize((int) getResources().getDimension(R.dimen.jc_start_button_w_h_fullscreen));
        } else if (currentScreen == SCREEN_LAYOUT_NORMAL
                || currentScreen == SCREEN_LAYOUT_LIST) {
            fullscreenButton.setImageResource(R.drawable.jc_enlarge);
            backButton.setVisibility(View.GONE);
            titleTextView.setVisibility(View.VISIBLE);
            tinyBackImageView.setVisibility(View.INVISIBLE);
            changeStartButtonSize((int) getResources().getDimension(R.dimen.jc_start_button_w_h_normal));
        } else if (currentScreen == SCREEN_WINDOW_TINY) {
            tinyBackImageView.setVisibility(View.VISIBLE);
            setAllControlsVisible(View.INVISIBLE, View.INVISIBLE, View.INVISIBLE,
                    View.INVISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
        }
    }

    public void changeStartButtonSize(int size) {
        ViewGroup.LayoutParams lp = startButton.getLayoutParams();
        lp.height = size;
        lp.width = size;
        lp = loadingProgressBar.getLayoutParams();
        lp.height = size;
        lp.width = size;
    }

    @Override
    public int getLayoutId() {
        return R.layout.jc_layout_standard;
    }

    @Override
    public void setUiWitStateAndScreen(int state) {
        super.setUiWitStateAndScreen(state);
        switch (currentState) {
            case CURRENT_STATE_NORMAL:
                changeUiToNormal();
                break;
            case CURRENT_STATE_PREPARING:
                changeUiToPreparingShow();
                startDismissControlViewTimer();
                break;
            case CURRENT_STATE_PLAYING:
                changeUiToPlayingShow();
                startDismissControlViewTimer();
                break;
            case CURRENT_STATE_PAUSE:
                changeUiToPauseShow();
                cancelDismissControlViewTimer();
                break;
            case CURRENT_STATE_ERROR:
                changeUiToError();
                break;
            case CURRENT_STATE_AUTO_COMPLETE:
                changeUiToCompleteShow();
                cancelDismissControlViewTimer();
                bottomProgressBar.setProgress(100);
                break;
            case CURRENT_STATE_PLAYING_BUFFERING_START:
                changeUiToPlayingBufferingShow();
                break;
        }
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int id = v.getId();
        if (id == R.id.surface_container) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:
                    startDismissControlViewTimer();
                    if (mChangePosition) {
                        int duration = getDuration();
                        int progress = mSeekTimePosition * 100 / (duration == 0 ? 1 : duration);
                        bottomProgressBar.setProgress(progress);
                    }
                    if (!mChangePosition && !mChangeVolume) {
                        onEvent(JCUserActionStandard.ON_CLICK_BLANK);
                        onClickUiToggle();
                    }
                    break;
            }
        } else if (id == R.id.bottom_seek_progress) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    cancelDismissControlViewTimer();
                    break;
                case MotionEvent.ACTION_UP:
                    startDismissControlViewTimer();
                    break;
            }
        }
        return super.onTouch(v, event);
    }

    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        super.onClick(v);
        switch (v.getId()) {
            case R.id.startSmall:
                if (startButton != null) {
                    startButton.performClick();
                }
                break;

            case R.id.tiaoguoBtn://跳过广告
                playMainUrl();
                break;

            case R.id.chakanBtn://查看详情

                toGameDetail();

                break;

            case R.id.thumb: {
                if (TextUtils.equals(videoType, TypeConstant.NEWS_VIDEO_TYPE1) || TextUtils.isEmpty(url)) {
                    urlEmptyHandler();
                    return;
                }
                if (currentState == CURRENT_STATE_NORMAL) {
                    if (!JCUtils.isWifiConnected(getContext()) && !WIFI_TIP_DIALOG_SHOWED) {
                        showWifiDialog();
                        return;
                    }
                    startVideo();
                    onEvent(JCUserActionStandard.ON_CLICK_START_THUMB);
                } else if (currentState == CURRENT_STATE_AUTO_COMPLETE) {
                    onClickUiToggle();
                }
                break;
            }
            case R.id.surface_container:
                startDismissControlViewTimer();
                break;
            case R.id.back:
            case R.id.back_tiny:
                backPress();
                break;
            case R.id.jc_replay: {
                //重播
                if (replyLayout != null && replyLayout.getVisibility() == View.VISIBLE) {
                    //隐藏重播模块
                    replyLayout.setVisibility(View.GONE);
                }
                if (startButton != null) {
                    startButton.performClick();
                }
                break;
            }
            case R.id.jc_share://分享
                share();
                break;
        }
    }

    /**
     * 分享
     */
    private void share() {
        if (mShareUtils == null) {
            mShareUtils = new AppShareUtils((Activity) getContext());
        }
        mShareUtils.showShareDialog(this.mShareBean, TypeConstant.PAGE_VIDEO_DETAIL);
    }

    /**
     * 设置分享数据
     *
     * @param shareBean
     */
    public void setShareBean(ShareBean shareBean) {
        this.mShareBean = shareBean;
        this.videoType = null;
    }

    /**
     * 设置分享数据
     *
     * @param shareBean
     */
    public void setShareBean(ShareBean shareBean, String videoType) {
        this.mShareBean = shareBean;
        this.videoType = videoType;
    }

    /**
     * 设置显示标题
     *
     * @param showTitle
     */
    public void setShowTitle(boolean showTitle) {
        this.isShowTitle = showTitle;
    }


    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        super.onStartTrackingTouch(seekBar);
        cancelDismissControlViewTimer();
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        super.onStopTrackingTouch(seekBar);
        startDismissControlViewTimer();
    }

    /**
     * 开始播放视频
     */
    public void startVideo() {
        if (mShareBean == null || TextUtils.isEmpty(mShareBean.getArticleId())) {
            return;
        }
        articleId = mShareBean.getArticleId();
        //如果还没有广告数据 则请求接口获取配置
        HashMap<String, String> parmsMap = new HashMap<>();
        parmsMap.put("articleId", mShareBean.getArticleId());
        parmsMap.put("sourceType", TypeConstant.SOURCETYPE_NORMAL);
        parmsMap.put("onlyAd", "1");//是否只取插片广告 1是 0否，默认为0
        HttpListener<DataBean<VideoContent>> httpListener = new HttpListener<DataBean<VideoContent>>() {

            @Override
            public void onStart() {
                //展示请求等待的UI
                changeUiToADShow();
            }

            @Override
            public void onError(VolleyError error) {
//                if(isAdFinishChangeUI){
//                    onCompletion();
//                }
                prepareMediaPlayer();//准备播放视频(用老的url)
            }

            @Override
            public void onSuccess(DataBean<VideoContent> response) {
                if (response.noError() && response.getData() != null) {
                    //重新获取视频URL
                    VideoContent data = response.getData();


                    mainUrl = data.getVideoCurl();
                    NativeAdVideo insertAds = data.getInsertAds();
                    if (insertAds != null && insertAds.getHead() != null) {
                        NativeAd head = insertAds.getHead();
                        String adType = head.getAdType();

                        if (TextUtils.equals(adType, AdConfig.AD_TYPE_VIDEO)) {
                            adUrl = head.getJumpUrl();
                            //文章Id
                            adId = head.getAdId();

//                            LogUtils.e("gzq", "adId ==== "+adId );
                        }
                    }

                    boolean isPlayAd = false;

                    isAdPlaying = false;
                    //判断这个articleId是否播放过广告


                    //首先判断是否超过次数了
                    //现在加入没超过
//                    isPlayAd = true;

                    apPlayNum = StringUtils.toInt(AppConfigManager.getInstance().readConfig(ConfigKeyConstant.adPlayNum, "0"), 0);


                    //同一个广告算一次,超过adPlayNum,就不播放了

                    //如果是今日第一次启动,那么就新建一个表

                    if (adPlayedSet == null) {
                        adPlayedSet = new HashMap<>();
                        String s = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.adPlayed, "");
                        if (!TextUtils.isEmpty(s)) {
                            String[] split = s.split("-");
                            if (split.length > 0) {
                                for (String adIdStr : split) {
                                    adPlayedSet.put(adIdStr, 1);
                                }
                            }
                        }

                    }

                    Integer integer = adPlayedSet.get(adId);
//                    LogUtils.e("gzq","integer = "+ integer + "     adPlayedSet.size = "+adPlayedSet.size()+"\nisPlayAdWithSameArticleId() = "+isPlayAdWithSameArticleId());
                    if (adPlayedSet.size() < apPlayNum && isPlayAdWithSameArticleId()) {//证明是没播放过的
                        isPlayAd = true;
//                        LogUtils.e("gzq", "此次需要播放");
                        adPlayedSet.put(adId, 1);
                        if (TextUtils.isEmpty(adIdStr)) {
                            adIdStr += adId;
                        } else {
                            adIdStr += "-" + adIdStr;
                        }
                        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.adPlayed, adIdStr);

                    }


                    if (!TextUtils.isEmpty(adUrl) && isPlayAd) {
                        url = adUrl;
                        isAdPlaying = true;
                    } else {
                        url = mainUrl;
                    }


                    if (TextUtils.isEmpty(url)) {
                        changeUiToInit();
                        urlEmptyHandler();
                    } else {
                        prepareMediaPlayer();//准备播放视频(用新的url)
                    }

                } else {
                    prepareMediaPlayer();//准备播放视频(用老的url)
                }
            }
        };
        //请求网络
        HttpUtils.addPostRequest(URIContant.VIDEO_DETAIL, new TypeToken<DataBean<VideoContent>>() {
        }.getType(), "", parmsMap, httpListener);
    }

    private boolean isPlayAdWithSameArticleId() {
        String aLong = adMap.get(articleId);
        long l = StringUtils.toLong(aLong, 0L);

        //证明对于这个视屏Id,已经播放过当前的广告了
        long currentTime = System.currentTimeMillis();
        if (currentTime - l > 1000 * 60 * 5) {//大于5分钟的话.那么就继续播放
            return true;
        }
        return false;
    }

//    /**
//     * 添加贴片广告
//     * @param nativeAdVideo
//     */
//    private void getadview(NativeAdVideo nativeAdVideo){
//        if(nativeAdVideo == null || nativeAdVideo.getHead() == null){
//            //如果没有加载成功 直接加载视频
//            onAdPlayEnd();
//            return;
//        }
//        if(adView == null){
//            adView = AdConfig.getViedoAdView(getContext(), nativeAdVideo, null);
//            adView.setVideoAdPlay(this);
//            adView.setVisibility(View.GONE);
//            //添加广告控件
//            addView(adView);
//        }else{
//            AdConfig.getViedoAdView(getContext(), nativeAdVideo, adView);
//        }
//        if(!adView.isAdSuces()){
//            //如果没有加载成功 直接加载视频
//            onAdPlayEnd();
//        }
//    }

    public void onClickUiToggle() {

        //是广告
        if (isAdPlaying && (currentState == CURRENT_STATE_PLAYING) && !TextUtils.isEmpty(adId)) {
            Log.e("gzq", "下载 --------- ");
            toGameDetail();
            return;
        }

        if (currentState == CURRENT_STATE_PREPARING) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToPreparingClear();
            } else {
                changeUiToPreparingShow();
            }
        } else if (currentState == CURRENT_STATE_PLAYING) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToPlayingClear();
            } else {
                changeUiToPlayingShow();
            }
        } else if (currentState == CURRENT_STATE_PAUSE) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToPauseClear();
            } else {
                changeUiToPauseShow();
            }
        } else if (currentState == CURRENT_STATE_AUTO_COMPLETE) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToCompleteClear();
            } else {
                changeUiToCompleteShow();
            }
        } else if (currentState == CURRENT_STATE_PLAYING_BUFFERING_START) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToPlayingBufferingClear();
            } else {
                changeUiToPlayingBufferingShow();
            }
        }
    }


    /**
     * 去往游戏详情
     */
    private void toGameDetail() {
        adMap.put(articleId, System.currentTimeMillis() + "");

        Intent intent = new Intent();
        intent.setClass(JCUtils.scanForActivity(getContext()), GameDetailActivity.class);
        intent.putExtra(Config.Extra.PARAMETER1, adId);
        intent.putExtra(Config.Extra.PARAMETER2, TypeConstant.SOURCETYPE_NORMAL);
        JCUtils.scanForActivity(getContext()).startActivity(intent);


    }

    @Override
    protected void playMainUrl() {
        adMap.put(articleId, System.currentTimeMillis() + "");
        super.playMainUrl();
    }

    public void onCLickUiToggleToClear() {
        if (currentState == CURRENT_STATE_PREPARING) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToPreparingClear();
            } else {
            }
        } else if (currentState == CURRENT_STATE_PLAYING) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToPlayingClear();
            } else {
            }
        } else if (currentState == CURRENT_STATE_PAUSE) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToPauseClear();
            } else {
            }
        } else if (currentState == CURRENT_STATE_AUTO_COMPLETE) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToCompleteClear();
            } else {
            }
        } else if (currentState == CURRENT_STATE_PLAYING_BUFFERING_START) {
            if (bottomContainer.getVisibility() == View.VISIBLE) {
                changeUiToPlayingBufferingClear();
            } else {
            }
        }
    }

    @Override
    public void setProgressAndText() {
        super.setProgressAndText();
        int position = getCurrentPositionWhenPlaying();
        int duration = getDuration();
        int progress = position * 100 / (duration == 0 ? 1 : duration);
        if (progress != 0) bottomProgressBar.setProgress(progress);
    }

    @Override
    public void setBufferProgress(int bufferProgress) {
        super.setBufferProgress(bufferProgress);
        if (bufferProgress != 0) bottomProgressBar.setSecondaryProgress(bufferProgress);
    }

    @Override
    public void resetProgressAndTime() {
        super.resetProgressAndTime();
        bottomProgressBar.setProgress(0);
        bottomProgressBar.setSecondaryProgress(0);
    }

    /**
     * 默认UI
     */
    public void changeUiToNormal() {

        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.VISIBLE, View.INVISIBLE, View.VISIBLE,
                        View.INVISIBLE, View.VISIBLE, View.GONE, View.INVISIBLE, View.VISIBLE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.VISIBLE, View.INVISIBLE, View.VISIBLE,
                        View.INVISIBLE, View.VISIBLE, View.GONE, View.INVISIBLE, View.VISIBLE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }
    }

    /**
     * 准备播放UI
     */
    public void changeUiToPreparingShow() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.VISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.VISIBLE, View.VISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.VISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.VISIBLE, View.VISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    public void changeUiToPreparingClear() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.VISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.VISIBLE, View.VISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.VISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.VISIBLE, View.VISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    //JustPreparedUi
    @Override
    public void onPrepared() {
        super.onPrepared();
        setAllControlsVisible(View.VISIBLE, View.INVISIBLE, View.INVISIBLE,
                View.INVISIBLE, View.INVISIBLE, View.GONE, View.VISIBLE, View.GONE);

        if (!isAdPlaying) {
            startDismissControlViewTimer();

        }
    }

    /**
     * 播放中UI
     */
    public void changeUiToPlayingShow() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.VISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.VISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    public void changeUiToPlayingClear() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.INVISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.VISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.INVISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.VISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    /**
     * 暂停UI
     */
    public void changeUiToPauseShow() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.VISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.VISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    public void changeUiToPauseClear() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.INVISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.INVISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    /**
     * 播放进度缓冲中UI
     */
    public void changeUiToPlayingBufferingShow() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.INVISIBLE,
                        View.VISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.INVISIBLE,
                        View.VISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    /**
     * 播放进度缓冲清除UI
     */
    public void changeUiToPlayingBufferingClear() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.INVISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.VISIBLE, View.INVISIBLE, View.GONE, View.VISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.INVISIBLE, View.INVISIBLE, View.INVISIBLE,
                        View.VISIBLE, View.INVISIBLE, View.GONE, View.VISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    /**
     * 播放完成UI
     */
    public void changeUiToCompleteShow() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.INVISIBLE,
                        View.INVISIBLE, View.VISIBLE, View.VISIBLE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.INVISIBLE,
                        View.INVISIBLE, View.VISIBLE, View.VISIBLE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    public void changeUiToCompleteClear() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.INVISIBLE,
                        View.INVISIBLE, View.VISIBLE, View.VISIBLE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.VISIBLE, View.VISIBLE, View.INVISIBLE,
                        View.INVISIBLE, View.VISIBLE, View.VISIBLE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    public void changeUiToError() {
        switch (currentScreen) {
            case SCREEN_LAYOUT_NORMAL:
            case SCREEN_LAYOUT_LIST:
                setAllControlsVisible(View.INVISIBLE, View.INVISIBLE, View.VISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_FULLSCREEN:
                setAllControlsVisible(View.INVISIBLE, View.INVISIBLE, View.VISIBLE,
                        View.INVISIBLE, View.INVISIBLE, View.GONE, View.INVISIBLE, View.GONE);
                updateStartImage();
                break;
            case SCREEN_WINDOW_TINY:
                break;
        }

    }

    /**
     * 加载广告的UI
     */
    private void changeUiToADShow() {
        if (isShowTitle && currentScreen == SCREEN_WINDOW_FULLSCREEN) {
            topContainer.setVisibility(View.VISIBLE);
        } else {
            if (isShowTitle && currentScreen == SCREEN_LAYOUT_LIST) {
                topContainer.setVisibility(View.VISIBLE);
            } else {
                topContainer.setVisibility(View.INVISIBLE);
            }

        }
        bottomContainer.setVisibility(View.INVISIBLE);
        startButton.setVisibility(View.INVISIBLE);
        loadingProgressBar.setVisibility(View.VISIBLE);
        thumbImageView.setVisibility(View.VISIBLE);
        bottomProgressBar.setVisibility(View.INVISIBLE);
        timeTextview.setVisibility(View.GONE);
    }

    /**
     * 展示初始状态
     */
    private void changeUiToInit() {
        if (isShowTitle && currentScreen == SCREEN_WINDOW_FULLSCREEN) {
            topContainer.setVisibility(View.VISIBLE);
        } else {
            if (isShowTitle && currentScreen == SCREEN_LAYOUT_LIST) {
                topContainer.setVisibility(View.VISIBLE);
            } else {
                topContainer.setVisibility(View.INVISIBLE);
            }
        }
        bottomContainer.setVisibility(View.INVISIBLE);
        startButton.setVisibility(View.INVISIBLE);
        loadingProgressBar.setVisibility(View.VISIBLE);
        thumbImageView.setVisibility(View.VISIBLE);
        bottomProgressBar.setVisibility(View.INVISIBLE);
        timeTextview.setVisibility(View.GONE);
    }

    /**
     * 设置播放器的按钮状态
     *
     * @param topCon
     * @param bottomCon
     * @param startBtn
     * @param loadingPro
     * @param thumbImg
     * @param replyView
     * @param bottomPro
     */
    public void setAllControlsVisible(int topCon, int bottomCon, int startBtn, int loadingPro,
                                      int thumbImg, int replyView, int bottomPro, int timeView) {
        if (isShowTitle && currentScreen == SCREEN_WINDOW_FULLSCREEN) {
            topContainer.setVisibility(topCon);
        } else if (topContainer.getVisibility() == VISIBLE) {
            if (isShowTitle && currentScreen == SCREEN_LAYOUT_LIST) {
                topContainer.setVisibility(View.VISIBLE);
            } else {
                topContainer.setVisibility(View.INVISIBLE);
            }
        }

        startButton.setVisibility(startBtn);
//            if(bottomCon == View.VISIBLE){//现在是可见的
        if (isAdPlaying && (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE)) {//如果是广告,那么不显示progress
//            progressBar.setVisibility(View.INVISIBLE);
            smallStartButton.setVisibility(View.VISIBLE);
            startButton.setVisibility(View.GONE);
            bottomContainer.setVisibility(INVISIBLE);

            tiaoguoBtn.setVisibility(View.VISIBLE);
            chakanBtn.setVisibility(View.VISIBLE);
        } else {
//            progressBar.setVisibility(View.VISIBLE);
            tiaoguoBtn.setVisibility(View.GONE);
            chakanBtn.setVisibility(View.GONE);
            smallStartButton.setVisibility(View.GONE);
            startButton.setVisibility(startBtn);
            bottomContainer.setVisibility(bottomCon);
        }


        loadingProgressBar.setVisibility(loadingPro);
        thumbImageView.setVisibility(thumbImg);
        bottomProgressBar.setVisibility(bottomPro);
        if (replyLayout.getVisibility() != replyView) {
            replyLayout.setVisibility(replyView);
        }
        if (!TextUtils.isEmpty(timeTextview.getText())) {
            timeTextview.setVisibility(timeView);
        } else {
            timeTextview.setVisibility(View.GONE);
        }
    }

    public void updateStartImage() {
        if (currentState == CURRENT_STATE_PLAYING) {
            startButton.setImageResource(R.drawable.jc_click_pause_selector);
            smallStartButton.setImageResource(R.drawable.jc_click_pause_selector);
        } else if (currentState == CURRENT_STATE_ERROR) {
            startButton.setImageResource(R.drawable.jc_click_error_selector);
            smallStartButton.setImageResource(R.drawable.jc_click_error_selector);
        } else {
            startButton.setImageResource(R.drawable.jc_click_play_selector);
            smallStartButton.setImageResource(R.drawable.jc_click_play_selector);
        }
    }


    protected Dialog mProgressDialog;
    protected ProgressBar mDialogProgressBar;
    protected TextView mDialogSeekTime;
    protected TextView mDialogTotalTime;
    protected ImageView mDialogIcon;

    @Override
    public void showProgressDialog(float deltaX, String seekTime, int seekTimePosition, String totalTime, int totalTimeDuration) {
        super.showProgressDialog(deltaX, seekTime, seekTimePosition, totalTime, totalTimeDuration);
        if (mProgressDialog == null) {
            View localView = LayoutInflater.from(getContext()).inflate(R.layout.jc_dialog_progress, null);
            mDialogProgressBar = ((ProgressBar) localView.findViewById(R.id.duration_progressbar));
            mDialogSeekTime = ((TextView) localView.findViewById(R.id.tv_current));
            mDialogTotalTime = ((TextView) localView.findViewById(R.id.tv_duration));
            mDialogIcon = ((ImageView) localView.findViewById(R.id.duration_image_tip));
            mProgressDialog = new Dialog(getContext(), R.style.jc_style_dialog_progress);
            mProgressDialog.setContentView(localView);
            mProgressDialog.getWindow().addFlags(Window.FEATURE_ACTION_BAR);
            mProgressDialog.getWindow().addFlags(32);
            mProgressDialog.getWindow().addFlags(16);
            mProgressDialog.getWindow().setLayout(-2, -2);
            WindowManager.LayoutParams localLayoutParams = mProgressDialog.getWindow().getAttributes();
            localLayoutParams.gravity = Gravity.CENTER;
            mProgressDialog.getWindow().setAttributes(localLayoutParams);
        }
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }

        mDialogSeekTime.setText(seekTime);
        mDialogTotalTime.setText(" / " + totalTime);
        mDialogProgressBar.setProgress(totalTimeDuration <= 0 ? 0 : (seekTimePosition * 100 / totalTimeDuration));
        if (deltaX > 0) {
            mDialogIcon.setBackgroundResource(R.drawable.jc_forward_icon);
        } else {
            mDialogIcon.setBackgroundResource(R.drawable.jc_backward_icon);
        }
        onCLickUiToggleToClear();
    }

    @Override
    public void dismissProgressDialog() {
        super.dismissProgressDialog();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    protected Dialog mVolumeDialog;
    protected ProgressBar mDialogVolumeProgressBar;
    protected TextView mDialogVolumeTextView;
    protected ImageView mDialogVolumeImageView;

    @Override
    public void showVolumeDialog(float deltaY, int volumePercent) {
        super.showVolumeDialog(deltaY, volumePercent);
        if (mVolumeDialog == null) {
            View localView = LayoutInflater.from(getContext()).inflate(R.layout.jc_dialog_volume, null);
            mDialogVolumeImageView = ((ImageView) localView.findViewById(R.id.volume_image_tip));
            mDialogVolumeTextView = ((TextView) localView.findViewById(R.id.tv_volume));
            mDialogVolumeProgressBar = ((ProgressBar) localView.findViewById(R.id.volume_progressbar));
            mVolumeDialog = new Dialog(getContext(), R.style.jc_style_dialog_progress);
            mVolumeDialog.setContentView(localView);
            mVolumeDialog.getWindow().addFlags(8);
            mVolumeDialog.getWindow().addFlags(32);
            mVolumeDialog.getWindow().addFlags(16);
            mVolumeDialog.getWindow().setLayout(-2, -2);
            WindowManager.LayoutParams localLayoutParams = mVolumeDialog.getWindow().getAttributes();
            localLayoutParams.gravity = Gravity.CENTER;
            mVolumeDialog.getWindow().setAttributes(localLayoutParams);
        }
        if (!mVolumeDialog.isShowing()) {
            mVolumeDialog.show();
        }
        if (volumePercent <= 0) {
            mDialogVolumeImageView.setBackgroundResource(R.drawable.jc_close_volume);
        } else {
            mDialogVolumeImageView.setBackgroundResource(R.drawable.jc_add_volume);
        }
        if (volumePercent > 100) {
            volumePercent = 100;
        } else if (volumePercent < 0) {
            volumePercent = 0;
        }
        mDialogVolumeTextView.setText(volumePercent + "%");
        mDialogVolumeProgressBar.setProgress(volumePercent);
        onCLickUiToggleToClear();
    }

    @Override
    public void dismissVolumeDialog() {
        super.dismissVolumeDialog();
        if (mVolumeDialog != null) {
            mVolumeDialog.dismiss();
        }
    }

    protected Dialog mBrightnessDialog;
    protected ProgressBar mDialogBrightnessProgressBar;
    protected TextView mDialogBrightnessTextView;

    @Override
    public void showBrightnessDialog(int brightnessPercent) {
        super.showBrightnessDialog(brightnessPercent);
        if (mBrightnessDialog == null) {
            View localView = LayoutInflater.from(getContext()).inflate(R.layout.jc_dialog_brightness, null);
            mDialogBrightnessTextView = ((TextView) localView.findViewById(R.id.tv_brightness));
            mDialogBrightnessProgressBar = ((ProgressBar) localView.findViewById(R.id.brightness_progressbar));
            mBrightnessDialog = new Dialog(getContext(), R.style.jc_style_dialog_progress);
            mBrightnessDialog.setContentView(localView);
            mBrightnessDialog.getWindow().addFlags(Window.FEATURE_ACTION_BAR);
            mBrightnessDialog.getWindow().addFlags(32);
            mBrightnessDialog.getWindow().addFlags(16);
            mBrightnessDialog.getWindow().setLayout(-2, -2);
            WindowManager.LayoutParams localLayoutParams = mBrightnessDialog.getWindow().getAttributes();
            localLayoutParams.gravity = Gravity.CENTER;
            mBrightnessDialog.getWindow().setAttributes(localLayoutParams);

        }
        if (!mBrightnessDialog.isShowing()) {
            mBrightnessDialog.show();
        }
        if (brightnessPercent > 100) {
            brightnessPercent = 100;
        } else if (brightnessPercent < 0) {
            brightnessPercent = 0;
        }
        mDialogBrightnessTextView.setText(brightnessPercent + "%");
        mDialogBrightnessProgressBar.setProgress(brightnessPercent);
        onCLickUiToggleToClear();
    }

    @Override
    public void dismissBrightnessDialog() {
        super.dismissBrightnessDialog();
        if (mBrightnessDialog != null) {
            mBrightnessDialog.dismiss();
        }
    }

    public void startDismissControlViewTimer() {
        cancelDismissControlViewTimer();
        DISMISS_CONTROL_VIEW_TIMER = new Timer();
        mDismissControlViewTimerTask = new DismissControlViewTimerTask();
        DISMISS_CONTROL_VIEW_TIMER.schedule(mDismissControlViewTimerTask, 2500);
    }

    public void cancelDismissControlViewTimer() {
        if (DISMISS_CONTROL_VIEW_TIMER != null) {
            DISMISS_CONTROL_VIEW_TIMER.cancel();
        }
        if (mDismissControlViewTimerTask != null) {
            mDismissControlViewTimerTask.cancel();
        }

    }

//    /**
//     * 贴片广告停止
//     */
//    @Override
//    public void onAdStop() {
//        if(adView != null){
//            //之前的广告停止并且隐藏
//            adView.onCompletion();
//        }
//        //不让广告展示了
//        isAdFinishChangeUI = false;
//    }
//
//    /**
//     * 贴片广告结束
//     */
//    @Override
//    public void onAdPlayEnd() {
//        prepareMediaPlayer();//准备播放视频
//    }

    @Override
    protected boolean urlEmptyHandler() {
        if (getContext() == null) {
            return true;
        }
        if (currentScreen == SCREEN_WINDOW_FULLSCREEN
                || currentScreen == SCREEN_LAYOUT_NORMAL
                || mShareBean == null) {
            return super.urlEmptyHandler();
        }
        Intent intent = new Intent(getContext(), VideoDetailActivity.class);
        StatService.onEvent(getContext(), "055", "播放器点击视频", 1);// 统计的点击的次数
        intent.putExtra(Config.Extra.PARAMETER1, mShareBean.getArticleId());
        intent.putExtra(Config.Extra.PARAMETER2, TypeConstant.SOURCETYPE_NORMAL);
        if (getContext() != null) {
            getContext().startActivity(intent);
        }
        return true;
    }


    /**
     * 这里是控制是否显示隐藏UI的
     */
    public class DismissControlViewTimerTask extends TimerTask {

        @Override
        public void run() {
            if (currentState != CURRENT_STATE_NORMAL
                    && currentState != CURRENT_STATE_ERROR
                    && currentState != CURRENT_STATE_AUTO_COMPLETE) {
                if (getContext() != null && getContext() instanceof Activity) {
                    ((Activity) getContext()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!isAdPlaying) {
                                bottomContainer.setVisibility(View.INVISIBLE);
                                topContainer.setVisibility(View.INVISIBLE);
                                startButton.setVisibility(View.INVISIBLE);
                                if (currentScreen != SCREEN_WINDOW_TINY) {
                                    bottomProgressBar.setVisibility(View.VISIBLE);
                                }
                            }

                        }
                    });
                }
            }
        }
    }
}
